<template>
  <div class="login">
    <div
      style="
        margin: 180px auto;
        background-color: #fff;
        width: 350px;
        
        padding: 20px;
        border-radius: 10px;
      "
    >
      <div class="title"><i class="el-icon-s-custom"></i> 登录</div>
      <el-form :model="user" :rules="rules" ref="userForm">
        <el-form-item prop="mobile">
          <el-input
            size="medium"
            style="margin: 10px auto"
            prefix-icon="el-icon-user"
            v-model="user.mobile"
            placeholder="请输入手机号"
          ></el-input
        ></el-form-item>
        <el-form-item prop="password"
          ><el-input
            size="medium"
            style="margin: 10px auto"
            prefix-icon="el-icon-lock"
            show-password
            v-model="user.password"
            placeholder="请输入密码"
          ></el-input
        ></el-form-item>
        <el-form-item style="margin: 10px 0; text-align: right">
          <el-button
            type="primary"
            size="small"
            autocomplete="off"
            @click="login"
            >登录</el-button
          >
          <el-button
            type="success"
            size="small"
            autocomplete="off"
            @click="toRegister"
            >注册</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>

import cookie from 'js-cookie'
import LoginApi from '@/api/login'
export default {
  name: "login",
  data() {
    return {
      user: {
        mobile: "",
        password: "",
      },

      rules: {
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { min: 3, max: 11, message: "长度在 11个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    toRegister() {
      this.$router.push("/register");
    },
    login() {
      this.$refs["userForm"].validate((valid) => {
        //如果合法
        if (valid) {
         //发起登录请求
         LoginApi.login(this.user).then(res=>{
          cookie.set("jwt-token",res.data.token,{domain:'localhost'});//写入cookie
          if(res.code===20000){
            this.$message.success(res.message);
            window.location.href="/"
          }
          else{
            this.$message.error(res.message);
          }
         })
        }
        //非法
        else {
          return false;
        }
      });
    },
  },
};
</script>
<style scoped>
.login {
  height: 100vh;
  overflow: hidden;
  background-image: linear-gradient(to bottom right, #d32144, #151fb4);
}
.title {
  text-align: center;
  font-size: 24px;
  margin: 20px auto;
}
</style>>

